package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.account.service.impl.UserAccountServiceImpl;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 类名: AccountReceiver
 * 描述: 该类用于处理 。
 * 核心:
 *
 * @author 胡爸爸
 * @date 2025-02-24
 */
@Component
@Slf4j
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;
    private final UserAccountServiceImpl userAccountServiceImpl;

    public AccountReceiver(UserAccountServiceImpl userAccountServiceImpl) {
        this.userAccountServiceImpl = userAccountServiceImpl;
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER, durable = "true", autoDelete = "flase"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void registerUser(Long userId, Message message, Channel channel) throws Exception {
        System.out.println("用户注册成功!" + userId);

        byte[] body = message.getBody();
        System.out.println("消息内容:\t" + new String(body).toString());
        System.out.println("Your消息内容:\t" + message.getMessageProperties().getDeliveryTag());


        try {
            if (null != userId) {
                userAccountService.registerUser(userId);


            }
        } catch (Exception e) {
            System.out.printf(e.getMessage());
            log.error(e.getMessage());

        }

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
